package com.funi.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.routing.RoutingSupport;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.IOException;

/**********************************************************************
 * &lt;p&gt;文件名：HttpConnectUtils.java &lt;/p&gt;
 * &lt;p&gt;文件描述：基础网络连通性测试
 * @project_name：code_total
 * @author zengshunyao
 * @create 2025/10/03 12:47
 * @history
 * @department：政务事业部
 * Copyright ChengDu Funi Cloud Code Technology Development CO.,LTD 2014
 *                    All Rights Reserved.
 */
@Slf4j
public abstract class HttpConnectUtils {

    /**
     * 测试GitLab基础网络连通性（验证能否访问 GitLab 首页）
     *
     * @param uri
     * @return
     */
    public static boolean testGitLabHomepageAccess(final String uri) {
        // 1. 创建HttpClient实例
        final HttpClient httpClient = HttpClientBuilder.create().build();
        try {
            // 2. 构造GET请求（访问GitLab首页）
            final HttpGet httpGet = new HttpGet(uri);
            // 3. 发送请求并获取响应
            //HttpResponse response = httpClient.execute(httpGet);
            final HttpResponse response = httpClient.executeOpen(RoutingSupport.determineHost(httpGet), httpGet, null);

            // 4. 验证响应状态码
            final int statusCode = response.getCode();
            log.debug("GitLab 首页访问响应码：{},地址： {}", statusCode, uri);

            // 断言：若状态码为200/3xx，说明网络连通且服务正常
            if (statusCode >= 200 && statusCode < 400) {
                log.info("✅ GitLab 基础网络连通性测试通过！");
                return true;
            } else {
                throw new RuntimeException("❌ GitLab 访问失败，响应码：" + statusCode
                        + "，请检查网络或GitLab服务状态");
            }
        } catch (IOException e) {
            // 捕获网络异常（如连接超时、域名解析失败）
            throw new RuntimeException("❌ GitLab 网络连通性测试失败：" + e.getMessage(), e);
        } catch (HttpException e) {
            // 捕获网络异常（如连接超时、域名解析失败）
            throw new RuntimeException("❌ GitLab 解析域名测试失败：" + e.getMessage(), e);
        }
    }

    /**
     * GitLab API 调用测试（验证权限与服务功能）
     *
     * @param gitlabApiEndpoint
     * @param personPrivateToken
     * @return
     */
    public static boolean testGitLabApiCall(final String gitlabApiEndpoint,
                                            final String personPrivateToken) {
        // 1. 创建HttpClient实例
        final HttpClient httpClient = HttpClientBuilder.create().build();

        try {
            // 2. 构造GET请求（访问GitLab Endpoint）
            final HttpGet httpGet = new HttpGet(gitlabApiEndpoint);
            httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + personPrivateToken);
            httpGet.setHeader(HttpHeaders.ACCEPT, "application/json");

            // 3. 发送请求并获取响应
            //CloseableHttpResponse response = httpClient.execute(httpGet);
            final ClassicHttpResponse response = httpClient.executeOpen(RoutingSupport.determineHost(httpGet), httpGet, null);
            int statusCode = response.getCode();
            final String responseBody = EntityUtils.toString(response.getEntity());
            log.debug("GitLab 访问响应码：{},地址： {}", statusCode, gitlabApiEndpoint);
            // 4. 验证响应状态码
            if (statusCode == 200) {
                // 2. Jackson实例（解析JSON响应）
                final ObjectMapper objectMapper = new ObjectMapper();
                final JsonNode userNode = objectMapper.readTree(responseBody);
                final String username = userNode.get("username").asText();
                final String email = userNode.get("email").asText();

                log.info("✅ GitLab API调用成功！");
                log.info("当前登录用户：" + username);
                log.info("用户邮箱：" + email);
                return true;
            } else if (statusCode == 401) {
                throw new RuntimeException("❌ GitLab API权限验证失败：私人令牌无效或已过期，请重新生成令牌");
            } else if (statusCode == 404) {
                throw new RuntimeException("❌ GitLab API端点不存在：" + gitlabApiEndpoint
                        + "，请检查GitLab版本或API路径是否正确");
            } else {
                throw new RuntimeException("❌ GitLab API调用失败，响应码：" + statusCode
                        + "，响应内容：" + responseBody);
            }
        } catch (IOException e) {
            // 捕获网络异常（如连接超时、域名解析失败）
            throw new RuntimeException("❌ GitLab 网络连通性测试失败：" + e.getMessage(), e);
        } catch (HttpException e) {
            // 捕获网络异常（如连接超时、域名解析失败）
            throw new RuntimeException("❌ GitLab 解析域名测试失败：" + e.getMessage(), e);
        }
    }
}
